﻿Imports System.IO
Imports System.Collections.Generic

Namespace AdvanceWars.Data
    ''' <summary>
    ''' 可序列化的游戏对象工厂
    ''' </summary>
    <Serializable()>
    Public Class Factory(Of T As GameObject)
        Inherits List(Of T)

        Sub New()
            MyBase.New()
        End Sub

        Sub New(ByVal collection As IEnumerable(Of T))
            Me.AddRange(collection)
        End Sub

        Public Shadows Sub Add(ByVal item As T)
            For i = 0 To Me.Count - 1
                If MyBase.Item(i).Id = item.Id Then
                    MyBase.Item(i) = item
                    Exit Sub
                End If
            Next
            MyBase.Add(item)
        End Sub

        Public Shadows Sub AddRange(ByVal collection As IEnumerable(Of T))
            For Each item As T In collection
                Me.Add(item)
            Next
        End Sub

        Default Shadows ReadOnly Property Item(ByVal id As Integer) As T
            Get
                Item = MyBase.Find( _
                    Function(obj As T)
                        Return obj.Id = id
                    End Function)
            End Get
        End Property

#Region "IO"

        ''' <summary>
        ''' 加载工厂对象
        ''' </summary>
        Public Shared Function LoadData(ByVal filename As String) As Factory(Of T)
            Dim f As Factory(Of T)
            Dim ser As ISerializer(Of Factory(Of T)) = New XmlSerializer(Of Factory(Of T))
            Try
                Using fs As New FileStream(Path.Combine(baseDir, filename), FileMode.Open, FileAccess.Read)
                    f = ser.Desrialize(fs)
                    fs.Close()
                End Using
            Catch ex As Exception
                Throw New GameException(String.Format("加载文件{0}失败! {1}", filename, ex.Message))
            End Try
            Return f
        End Function

        ''' <summary>
        ''' 将Factory输出到文件
        ''' </summary>
        Public Sub ExportData(ByVal filename As String)
            Dim ser As ISerializer(Of Factory(Of T)) = New XmlSerializer(Of Factory(Of T))
            Try
                Using fs As New FileStream(Path.Combine(baseDir, filename), FileMode.Create, FileAccess.Write)
                    ser.Serialize(fs, Me)
                    fs.Close()
                End Using
            Catch ex As Exception
                Throw New GameException(String.Format("输出文件{0}失败! {1}", filename, ex.Message))
            End Try
        End Sub

#End Region

    End Class
End Namespace